<template>
  <div class="login-container">
    <div class="login-box">
      <a href="/AdminLogin" style="margin-left: 230px">切换到管理员端>>>></a>
      <h2 class="login-title">西南大学登录系统-用户端</h2>

      <!-- 登录方式切换 -->
      <el-tabs v-model="activeTab" class="login-tabs">

        <el-tab-pane label="用户名密码" name="username"></el-tab-pane>
        <el-tab-pane label="手机号密码" name="phone-password"></el-tab-pane>
        <el-tab-pane label="手机号验证码" name="phone-code"></el-tab-pane>
      </el-tabs>

      <!-- 表单内容 -->
      <div class="login-form">
        <el-form v-if="activeTab === 'username'" :model="form" :rules="rules" ref="formRef">
          <el-form-item prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码" clearable />
          </el-form-item>
        </el-form>

        <el-form v-else-if="activeTab === 'phone-password'" :model="form" :rules="rules" ref="formRef">
          <el-form-item prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" clearable />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码" clearable />
          </el-form-item>
        </el-form>

        <el-form v-else :model="form" :rules="rules" ref="formRef">
          <el-form-item prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" clearable />
          </el-form-item>
          <el-form-item prop="code">
            <div class="code-box">
              <el-input v-model="form.code" placeholder="请输入验证码" clearable style="flex: 1" />
              <el-button @click="sendCode" :disabled="countdown > 0" style="margin-left: 100px">
                {{ countdown > 0 ? `${countdown}s后重新发送` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 登录按钮 -->
      <el-button type="primary" class="login-btn" @click="submitForm">登录</el-button>
    </div>
  </div>
</template>

<script>
import { ref } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";

export default {

  setup() {
    localStorage.clear();
    const router = useRouter();
    const activeTab = ref("username");
    const form = ref({
      username: "",
      password: "",
      phone: "",
      code: "",
    });
    const countdown = ref(0);
    const formRef = ref(null);

    const rules = {
      username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      phone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        { pattern: /^[0-9]{11}$/, message: "手机号必须是11位数字", trigger: "blur" },
      ],
      code: [
        { required: true, message: "请输入验证码", trigger: "blur" },
        { pattern: /^[0-9]{6}$/, message: "验证码必须是6位数字", trigger: "blur" },
      ],
    };

    const sendCode = async () => {
      if (countdown.value > 0) return;
      if (!form.value.phone) {
        return alert("请输入手机号！");
      }

      try {
        const response = await axios.get("/user/user/sendLoginCode", {
          params: { phone: form.value.phone },
        });
        console.log("验证码发送成功：", response.data);
        countdown.value = 60;
        const timer = setInterval(() => {
          countdown.value--;
          if (countdown.value <= 0) clearInterval(timer);
        }, 1000);
      } catch (error) {
        console.error("发送验证码失败：", error);
      }
    };

    const submitForm = async () => {
      formRef.value.validate(async (valid) => {
        if (!valid) {
          console.error("表单验证失败");
          return;
        }
          let response;
          if (activeTab.value === "username") {
            response = await axios.post("/user/user/loginUserByName.api", {
              userName: form.value.username,
              passWord: form.value.password,
            });
          } else if (activeTab.value === "phone-password") {
            response = await axios.post("/user/user/loginUser.api", {
              phone: form.value.phone,
              passWord: form.value.password,
            });
          } else if (activeTab.value === "phone-code") {
            response = await axios.get("/user/user/codeLogin", {
              params: {
                phone: form.value.phone,
                code: form.value.code,
              },
            });
          }
          if(response.data.code == 200){
            console.log("登录成功：", response.data);
            alert("登录成功！");
            localStorage.setItem("roleId", response.data.data.user.roleId)
            localStorage.setItem("roleName", response.data.data.user.roleName)
            localStorage.setItem("storeId", response.data.data.storeId)
            localStorage.setItem("userId", response.data.data.user.userId)
            localStorage.setItem("userName", response.data.data.user.userName)
            localStorage.setItem("userImg", response.data.data.user.userImg)
            if(localStorage.getItem("roleId")==="1"){
                await router.push("/Jump");
            }else if(localStorage.getItem("roleId")==="2"){
                if (localStorage.getItem("storeId")==="null"){
                  await router.push("/ApplyStore");
                }else {
                  await router.push("/MealsMain");
                }
            }else if(localStorage.getItem("roleId")==="4"){
                await router.push("/repair-list-worker");
            }


          }else {
            alert(response.data.msg);
            console.error("登录失败：",response.data.msg);
          }

      });
    };

    return { activeTab, form, rules, formRef, countdown, sendCode, submitForm };
  },
};
</script>

<style scoped>
/* 样式保持不变 */
.login-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("@/assets/img/background.jpg");
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-box {
  width: 400px;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}
.login-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}
.login-tabs {
  margin-bottom: 20px;
}
.login-form {
  margin-bottom: 20px;
}
.login-btn {
  width: 100%;
}
.code-box {
  display: flex;
  align-items: center;
}
</style>
